<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\company\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;
/**工具**/
use app\wechat\controller\WechatTool;
use Endroid\QrCode\QrCode;
/**
 * 企业员工管理
 * Class User
 * @package app\worker\controller
 */
class User extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'CompanyUser';
	protected $table1 = 'CompanyUserDepartment';
    protected $view_table ='view_user';
    protected $view_table_dept = 'view_company_dept';
    /**
     * 企业员工管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {

        $dbconf = $this->getconfig('vister_db');
        $where ='';
        $uinfo = $this->getGuserinfo();

        if($uinfo['db1']['authorize']!=1 && $uinfo['db1']['authorize']!=0){
            $check = $uinfo['db2']['companyid']==NULL?'':$uinfo['db2']['companyid'];

            if($check){
                 $where = 'companyid = '.$uinfo['db2']['companyid'];
            }else{
                $this->error('未加入公司,无权限查看当前内容');
            }         
           
        }

        $dept_list = Db::connect($dbconf)->table($this->view_table_dept)->select();
        $this->assign('data',[
            /**丢给视图的数据**/
            'deptlist'=>$dept_list,

        ]);

		$this->title = '部门员工管理';

        if($this->request->param('dep_id')){
            $dept_info = Db::connect($dbconf)->table('dept')->where('id = '.$this->request->param('dep_id'))->find();
            $this->assign('dept_info',$dept_info);
            $this->title = $dept_info['name'].'-部门员工管理';
            if($where){

                $where = $where.' and  deptid = '.$this->request->param('dep_id');
            }else{
                $where = '  deptid = '.$this->request->param('dep_id');

            }
            $count_apply = Db::connect($dbconf)->table('apply')->where('deptid = '.$this->request->param('dep_id').' and status = 0 and deletetime is null')->count();
            $this->assign('dep_id',$this->request->param('dep_id'));
            $this->assign('count_apply',$count_apply);
        }

        $create_at_first=trim($this->request->param('create_at_first'))?strtotime($this->request->param('create_at_first')):'';
        $create_at_last=trim($this->request->param('create_at_last'))?strtotime($this->request->param('create_at_last'))+3600*24:'';
		$status = trim($this->request->param('status'))==1?'deleteTime is not null':(trim($this->request->param('status'))==2?'deleteTime is null':''); 		



            $res_apply  = Db::connect($dbconf)->table('view_apply')->where('apply_status = 0 and apply_deletetime is null and apply_deptid = '.$this->request->param('dep_id'))
                                                                         // ->where($status)
                                                                         // ->like('name,dept_name,company_name')
                                                                         // ->equal('')
                                                                         ->order('apply_createtime desc')
                                                                         // ->page();
                                                                         ->select();

           $this->assign('list_apply',$res_apply);
		 			 if(!$create_at_first||!$create_at_last){



		 			
		 				  $this->_query(Db::connect($dbconf)->table($this->view_table))->where($where)
                                                                           ->where($status)
                                                                           ->like('name,dept_name,company_name')
                                                                           ->equal('')
                                                                           ->order('createtime desc')
                                                                           ->page();
		 			
		 				}
		 				else{
		 				
                          $this->_query(Db::connect($dbconf)->table($this->view_table))->where($where)
                                                                                        ->where($status)
                                                                                        ->where('createtime','between',[$create_at_first,$create_at_last])
                                                                                        ->like('name,dept_name,company_name')
                                                                                        ->equal('')
                                                                                        ->order('createtime desc')
                                                                                        ->page();
		 														
		 			}
		
    }

    /**
     * 添加企业员工
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {

// http://devs.zsicp.com/h5/?code=081SSSkl2FzwZ54EDJml2Lw9l42SSSkM&state=123#/pages/Departmentmanagement/sharedepartment?detailDate={"deptid":18,"departname":"技术部","companyid":216}    
        $uinfo = $this->getGuserinfo();
        $dbconf = $this->getconfig('vister_db');
        $qrcode_content = '';
        if($this->request->param('dept_id')){
            $is_manager = $this->request->param('is_m'); //3 部门经理 5保安部门经理
            $qrcode_content = "http://devs.zsicp.com/h5/#/pages/Departmentmanagement/sharedepartment?detailDate=";
            $dept_info = Db::connect($dbconf)->table('dept')->where('id = '.$this->request->param('dept_id'))->find();

            $go_dept_info = [
                'deptid'=>$dept_info['id']?:NULL,
                'departname'=>$dept_info['name']?:NULL,
                'companyid'=>$dept_info['companyid']?:NULL,
                'is_m'=> $is_manager,
                'type'=>'share',
            ];
            $qrcode_content = $qrcode_content.json_encode($go_dept_info,JSON_UNESCAPED_UNICODE);
            if($uinfo['db2']){
              $qrcode_sharecode = substr($uinfo['db2']['openid'],-6);
            }else{
              $this->error('用户信息错误');
            }

            $qrcode_content = $qrcode_content.'&sharecode='.$qrcode_sharecode;
            $qrcode_content = WechatTool::toshorturl($qrcode_content);

        }
        $company_list = Db::connect($dbconf)->table('view_company')->select();
        $this->assign('data',[
            /**丢给视图的数据**/
            'companylist'=>$company_list,
            'dept_qrcode'=>$qrcode_content,
        ]);
        
        

        if($this->request->isPost()){

            $companyid = $this->request->param('companyid');
            if(!$companyid){$this->error('未找到公司相关信息');}
            $companyinfo = Db::connect($dbconf)->table('view_company')->where('id = '.$companyid)->find();
            $dept_id = $this->request->param('departmentid');
            $uid = $this->request->param('userid');
            if(!$uid){$this->error('用户不存在或已删除');}
            $checkuinfo = Db::connect($dbconf)->table('view_user')->where('id = '.$uid)->find();
            if($checkuinfo['companyid']!=NULL && $checkuinfo['companyid']!=$companyid){$this->error('该用户已是其他公司员工');}
            $data = [
                'companyid' => $companyid,
                'deptid' => $dept_id,
                //'roleid' => $this->request->param('is_security')=='1'?6:($this->request->param('roleid')?$this->request->param('roleid'):4),
            ];
            if($this->request->param('is_security')=='1'){
                if($this->request->param('roleid')){
                    $data['roleid'] = $this->request->param('roleid');
                }else{
                    $data['roleid'] = 6;
                }
            }else{
                if($this->request->param('roleid')){
                     $data['roleid'] = $this->request->param('roleid');
                 }else{
                    $data['roleid'] = 4;
                 }
            }
            $where = 'id = '.$uid;
            $res = Db::connect($dbconf)->table('user')->where($where)->data($data)->update();
            $v_uinfo = Db::connect($dbconf)->table('view_user')->where($where)->find();
            //发送提醒消息
            $data = [
                     'template_id' => 'Exkadv3HIt-2WQtMdfi3hFMwZmLl1eTZRXNj8SV4bwI',
                     'array' => [
                         'first' => "(订阅通知:)你好-",
                         'keyword1' => "阅读消息",
                         'keyword2' => "{$v_uinfo["name"]}",
                         'keyword3' => date("Y年m月d日 H:i:s",time()),
                         'remark' => "您已成为{$companyinfo["name"]}员工",
                     ],
            
            ];
            $url = '';
            try{
                $sendRes = WechatTool::send_WXtpl($v_uinfo['openid'],$data,$url);
            }catch(\Throwable $th){
                Log::info("发送入职微信消息失败".time()."-".$v_uinfo['openid']);
            }

            $this->success('成功添加部门员工','');
        }

        $this->_form(Db::connect($dbconf)->table($this->view_table), 'qrcodeform');
	
		// $this->_query($this->table1)->like('department')->equal('status')->page();
    }

	protected function _form_page_filter(&$deptlist){
		
	
		
  //  精准回调对 $data 进行二次处理，注意是引用
	}
	
	
    /**
     * 修改企业员工
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        $dbconf = $this->getconfig('vister_db');
        $company_list = Db::connect($dbconf)->table('view_company')->select();

        $this->assign('data',[
            /**丢给视图的数据**/
            'companylist'=>$company_list,

        ]);
        //var_dump($this->request->param(''));
        if($this->request->isPost()){

            $companyid = $this->request->param('companyid');

            $dept_id = $this->request->param('departmentid');
            $uid = $this->request->param('userid');
            $data = [
                'companyid' => $companyid,
                'deptid' => $dept_id,
                
            ];
            if($this->request->param('is_security')=='1'){
                if($this->request->param('roleid')){
                    $data['roleid'] = $this->request->param('roleid');
                }else{
                    $data['roleid'] = 6;
                }
            }else{
                if($this->request->param('roleid')){
                     $data['roleid'] = $this->request->param('roleid');
                 }else{
                    $data['roleid'] = 4;
                 }
            }
            // if($this->request->param('ch_role')=='on'){
                
            // }else{
            //     switch ($this->request->param('roleid')) {
            //         case '2':
            //             $data['roleid'] = 2;
            //             # code...
            //             break;
            //         case '3':
            //         case '4':
            //         case '5':
            //         case '6':
            //             $data['roleid'] = $this->request->param('is_security')=='1'?6:($this->request->param('roleid')?$this->request->param('roleid'):4);
            //             # code...
            //             break;
            //         default:
            //             $data['roleid'] = $this->request->param('is_security')=='1'?6:($this->request->param('roleid')?$this->request->param('roleid'):4);
            //             # code...
            //             break;
            //     }

            // }
            if($this->request->param('contact_phone')){$data['mobile'] = $this->request->param('contact_phone');}
            if($this->request->param('contact_mail')){$data['email'] = $this->request->param('contact_mail');}
            $where = 'id = '.$uid;
            $res = Db::connect($dbconf)->table('user')->where($where)->data($data)->update();
            $this->success('成功修改部门员工','');
        }
        //$this->success('');
        $this->_form(Db::connect($dbconf)->table($this->view_table), 'form');
    }

    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
         $dbconf = $this->getconfig('vister_db');

		
        if ($this->request->isGet()) {
            $where = ['status' => '1', 'is_deleted' => '0'];
            $this->auths = Db::name('company_user_auth')->where($where)->order('sort desc,id desc')->select();
            array_unshift($this->auths, ['id' => '0', 'title' => '所有权限', 'path' => '/']);
            $data['svn_authorize'] = isset($data['svn_authorize']) ? explode(',', $data['svn_authorize']) : [];
        } else {
            if (isset($data['svn_authorize']) && is_array($data['svn_authorize'])) {
                $data['svn_authorize'] = join(',', $data['svn_authorize']);
            } else {
                $data['svn_authorize'] = '';
            }
            $macs = [];
            foreach (explode(PHP_EOL, preg_replace("/\s+/", PHP_EOL, trim(@$data['mobile_macs']))) as $mac) {
                if (DataService::applyMacValue($mac)) $macs[] = $mac;
            }
            $data['mobile_macs'] = join(PHP_EOL, array_unique($macs));
        }


        $uinfo = $this->getGuserinfo();


        if($uinfo['db1']['authorize']!=1){
            $check = $uinfo['db2']['companyid']==NULL?:'';
            if(!$check){
                 $where = 'companyid = '.$uinfo['db2']['companyid'];
            }else{
                $this->error('未加入公司,无权限查看当前内容');
            }         
           
        }else{

            if(@$data['companyid']){
                $where = 'companyid = '.$data['companyid'];
                
            }else{
                $this->deptlist = [];
            }
            
        }

        if($uinfo['db1']['authorize']==1){
           if(@$data['companyid']){
                $where = 'companyid = '.$data['companyid'];
                
            }else{
                $where = 'companyid = 0';
            }


        }

        $this->deptlist = Db::connect($dbconf)->table('view_company_dept')->where($where)->where('status',1)->select();
        switch ($uinfo['db1']['authorize']) {
            case 1:
                $this->rolelist = Db::connect($dbconf)->table('role')->select();
                # code...
                break;
            case 2:
                $this->rolelist = Db::connect($dbconf)->table('role')->where('id in (2,3,4,5,6)')->select();
                break;
            case 3:
                $this->rolelist = Db::connect($dbconf)->table('role')->where('id in (4,5,6)')->select();
                break;
            case 5:
                $this->rolelist = Db::connect($dbconf)->table('role')->where('id in (5,6)')->select();
                break;
            case 8:
                $this->rolelist = Db::connect($dbconf)->table('role')->where('id in (3,4,5,6,8)')->select();
                break;
            default:
                $this->rolelist = [];
                # code...
                break;
        }
        
        $this->type = $this->request->param('type');
		

			
    }

    /**
     * 更改企业员工状态
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function state()
    {
        $this->success('成功返回');;
        exit();
        $dbconf = $this->getconfig('vister_db');
        $status = trim($this->request->param('status'))==1?time():'is null';

        $this->_save(Db::connect($dbconf)->table('user'), ['deleteTime' => $status],'','id = '.$this->request->param('id'));
    }

    /**
     * 删除企业员工
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $dbconf = $this->getconfig('vister_db');
        $uinfo = $this->getGuserinfo();
        // $this->_delete($this->table);
        $userid=$uinfo['db2']['id'];
		if($this->request->isPost()){
		$id=trim($this->request->param('id'));
		   if($userid==$id){
		     	$this->success('删除失败！,管理者不能删除');  
		   }else{
		        $companyid = $this->request->param('companyid');
                $dept_id = $this->request->param('dept_id');
        		// dump($id);
                $where ='companyid .'.$companyid.' and '.$dept_id;
                $updata = [
                    'roleid' => 0,
                    'companyid' => 0,
                    'deptid' => 0,
                ];
        		$data = Db::connect($dbconf)->table('user')->where("id in ($id)")->data($updata)->update();
        		if($data){
        			$this->success('数据删除成功！');
        		} 
		   }
      
		}
    }

    /**
     * 获取员工姓名-列表-单个信息
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-09-17T14:19:00+0800
     * @LastTime     2020-09-17T14:19:00+0800
     * @return       [type]                       [description]
     */
    public function getuserlist(){
        $userinfo = $this->getGuserinfo();
        $id = $this->request->param('id');
        $name = $this->request->param('name');
        $phone = $this->request->param('phone');
        $type = $this->request->param('type');
        $dbconf = $this->getconfig('vister_db');
        switch ($userinfo['db1']['authorize']) {
            case '1':
                $where = '';
                # code...
                break;
            case '2':
                //$where = 'companyid = '.$userinfo['db2']['companyid'];
                $where = '';
                # code...
                break;
            default:
                $where = '';
                # code...
                break;
        }
        if($id){
            $data = Db::connect($dbconf)->table('view_user')->where('id ='.$id)->find();
            return tojson(['code'=>200,'data'=>$data]);
        }
        $data=Db::connect($dbconf)->table('view_user')->where($where)->where('name like "%'.$name.'%"')->select();
        if($type=='phone'){
            $data=Db::connect($dbconf)->table('view_user')->where($where)->where('mobile like "%'.$phone.'%"')->select();
        }

        return tojson(['code'=>200,'data'=>$data]);
    }


    /**
     * 设定受访人(功能)
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-09T15:51:13+0800
     * @LastTime     2020-10-09T15:51:13+0800
     * @return       [type]                       [description]
     */
    public function setapp(){
        $dbconf = $this->getconfig('vister_db');
        //array(4) { ["spm"]=> string(10) "m-57-58-59" ["id"]=> string(2) "13" ["companyid"]=> string(1) "1" ["deptid"]=> string(1) "1" }
        $userinfo = $this->getGuserinfo();
        $id = $this->request->param('id');
        $companyid = $this->request->param('companyid');
        $Interviewees = $this->request->param('interviewees');
        if(!$companyid){$this->error('参数错误');}


        $check_app = Db::connect($dbconf)->table('view_user')->where('id ='.$id)->find();

        if($check_app['Interviewees']==1 && $Interviewees==1){$this->error('该员工已是公司受访人');}


        $data = [
          'Interviewees' => $Interviewees,
        ];
        $res =  Db::connect($dbconf)->table('user')->where('id ='.$id)->data($data)->update();
        $tips = $data['Interviewees'] ==1?'成功设公司受访人':'取消受访人成功';
        $this->success($tips);
        exit;
        //废弃
        //获取该公司 可使用的受访人总数
        //获取该公司 使用的套餐
        $get_company_commodity = Db::connect($dbconf)->table('view_commodity_orders')->where('companyid = '.$companyid.' and status = 2 and deletetime is null and expritime > '.time())->order('createtime desc')->find();

        //if(!$get_company_commodity){$this->error('公司业务');}
        if($get_company_commodity){
            $need_count_app = $get_company_commodity['commodity_outAppnumber'];
        }else{
            $need_count_app = 1;
        }
        
        $count_app = Db::connect($dbconf)->table('view_user')->where(['Interviewees' => 1,'companyid' => $companyid])->count();



        //取消
        if($Interviewees==0){
            //check last app user
            if($need_count_app == 1 && $userinfo['db1']['authorize'] ==2 && $id!=$userinfo['db2']['id']){

                $res = Db::connect($dbconf)->table('user')->where('id ='.$userinfo['db2']['id'])->data(['Interviewees' => 1])->update();
            }
            
            $data = [
                'Interviewees' => 0,
                ];
            $res =  Db::connect($dbconf)->table('user')->where('id ='.$id)->data($data)->update();

            $this->success('取消受访人成功');
        }
        //
        //设定
        if($need_count_app - $count_app > 0){



            $data = [
            'Interviewees' => 1,
            ];
            $res =  Db::connect($dbconf)->table('user')->where('id ='.$id)->data($data)->update();
            $this->success('成功设公司受访人');
        }else{
            $this->error('公司受访人已上限');
        }

    }
}
